package summer.student.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import summer.student.Dao.AdminDao;
import summer.student.Domain.Admin;
import summer.student.Utils.JwtUtil;
import summer.student.Utils.Result;

import java.util.Map;

/**
 * @program: student
 * @description:
 * @author: hlt
 * @create: 2023-07-23 17:25
 **/
@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "*", maxAge = 3600)  // 后端解决跨域
@Api(tags = "登录相关接口")
public class LoginController {
    @Autowired
    private AdminDao adminDao;

    @PostMapping("/login")
    public Result adminLogin(@RequestBody Map<String,String> data){
        String adminId = data.get("adminId");
//        System.out.println("adminId: " + adminId);
        String password = data.get("password");
        if (adminId.length() > 20 || password.length() > 20) return Result.Error("数据非法");
        LambdaQueryWrapper<Admin> alqw = new LambdaQueryWrapper<>();
        alqw.eq(Admin::getAdminId, adminId);
        Admin admin = adminDao.selectOne(alqw);
        if(admin == null) return Result.Error("账号或密码错误");
        if(password.equals(admin.getPassword())) {
            String token = JwtUtil.createToken(admin);
            return Result.Success(token);
        }
        else return Result.Error("账号或密码错误");
    }
}
